import React, { Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import _ from 'lodash';

import PageHeader from '@/components/PageHeader';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Form,
} from 'antd';
import { FormInstance } from 'antd/es/form';

const { Option } = Select;

const cellType = {
  10901: '　　　大箱',
  10902: '　　　中箱',
  10903: '　　　小箱',
  10904: '　　超小箱',
  10905: '　大(宽)箱',
  10906: '　中(宽)箱',
  10907: '　小(宽)箱',
  10908: '超小(宽)箱',
  10909: '　　文件箱',
  10910: '文件(宽)箱',
  10911: '　　超大箱',
  10912: '超大(宽)箱',
};

const cellPosition = {
  1: '　　　左上',
  2: '　　　中上',
  3: '　　　右上',
  4: '　　　左中',
  5: '　　　　中',
  6: '　　　右中',
  7: '　　　左下',
  8: '　　　中下',
  9: '　　　右下',
};

interface DeputySaveProps {
  dispatch: Dispatch;
  detailInfo: any;
  location: {
    query: {
      id?: number;
    };
  };
}

interface DeputySaveState {
  cellTypeNum: any
  cellPositionNum: any;
}

@connect(
  ({
    deputyEdit: { detailInfo },
  }: any) => ({
    detailInfo,
  }),
)
class DeputySaveElem extends React.Component<DeputySaveProps, DeputySaveState> {
  formRef = React.createRef<FormInstance>();

  state: DeputySaveState = {
    cellTypeNum: [],
    cellPositionNum: [],
  }

  componentDidMount() {
    const { location: { query: { id } } } = this.props;
    if (id) {
      this.fetchDetailInfo();
    } else {
      this.fetchNextCode();
    }
  }

  componentDidUpdate(prevProps: any) {
    const {
      location: { query: { id } },
      detailInfo,
    } = this.props;
    if (id && id !== prevProps.location.query.id) {
      this.fetchDetailInfo();
    }

    if (!_.isEqual(prevProps.detailInfo, detailInfo)) {
      this.setFieldsValue();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: 'deputyEdit/clear' });
  }

  // 设置表单值
  setFieldsValue = () => {
    const { detailInfo } = this.props;

    if (Object.keys(detailInfo).length) {
      const {
        name,
        code,
        cellTypeConfList,
        cellPositionList,
      } = detailInfo;

      const cellTypeConf = cellTypeConfList?.reduce((origin: any, conf: any) => {
        origin[conf.cellType] = conf.cellNumbers.split(',').map((item: string) => Number(item));
        return origin;
      }, {}) || {};

      const cellPositionConf = cellPositionList?.reduce((origin: any, conf: any) => {
        origin[conf.position] = conf.cellNumbers.split(',').map((item: string) => Number(item));
        return origin;
      }, {}) || {};

      const params = {
        name,
        code,
        ...cellTypeConf,
        ...cellPositionConf,
      };
      this.formRef.current!.setFieldsValue(params);

      const cellTypeNum = cellTypeConfList?.reduce((origin: any, conf: any) => {
        origin = [...origin, ...conf.cellNumbers.split(',').map((item: string) => Number(item))];
        return origin;
      }, []) || [];
      const cellPositionNum = cellPositionList?.reduce((origin: any, conf: any) => {
        origin = [...origin, ...conf.cellNumbers.split(',').map((item: string) => Number(item))];
        return origin;
      }, []) || [];

      this.setState({ cellTypeNum, cellPositionNum });
    }
  };

  fetchNextCode = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'deputyEdit/fetchNextCode' });
  }

  fetchDetailInfo = () => {
    const { dispatch, location: { query } } = this.props;
    dispatch({
      type: 'deputyEdit/fetch',
      payload: { id: query.id },
    });
  }

  handleChangeTypeNum = () => {
    const cellTypeNum = Object.keys(cellType)
      .reduce((origin: any, type: any) => {
        const value = this.formRef.current!.getFieldValue(type) || [];
        origin = [...origin, ...value];
        return origin;
      }, []);

    this.setState({ cellTypeNum });
  }

  handleChangePositionNum = () => {
    const cellPositionNum = Object.keys(cellPosition)
      .reduce((origin: any, type: any) => {
        const value = this.formRef.current!.getFieldValue(type) || [];
        origin = [...origin, ...value];
        return origin;
      }, []);

    this.setState({ cellPositionNum });
  }

  handleSubmit = (values: any) => {
    const { location: { query } } = this.props;
    const { name, code, ...others } = values;
    const params: any = { name, code };

    if (query.id) {
      params.id = query.id;
      params.cellTypeConfList = Object.keys(others)
        .filter((key: any) => others[key] && key > 10)
        .map(key => ({ cellType: key, cellNumbers: others[key].toString() }));
      params.cellPositionList = Object.keys(others)
        .filter((key: any) => others[key] && key < 10)
        .map(key => ({ position: key, cellNumbers: others[key].toString() }));
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'deputyEdit/saveOrUpdate',
      payload: params,
    });
  }

  render() {
    const { cellTypeNum, cellPositionNum } = this.state;
    const { location: { query } } = this.props;

    const cellTypeNumList = [...new Array(32)]
      .map((item, index) => index + 1)
      .filter(num => !cellTypeNum.includes(num));

    const cellPositionNumList = [...new Array(32)]
      .map((item, index) => index + 1)
      .filter(num => !cellPositionNum.includes(num));

    return (
      <Fragment>
        <PageHeader />
        <Card title="基本信息" bordered={false}>
          <Form
            ref={this.formRef}
            hideRequiredMark
            className="tableListForm"
            onFinish={this.handleSubmit}
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Form.Item
                  label="副柜名称"
                  name="name"
                  rules={[{ required: true, message: '请输入副柜名称！' }]}
                >
                  <Input allowClear />
                </Form.Item>
              </Col>
              <Col md={8} sm={24}>
                <Form.Item
                  label="副柜编码"
                  name="code"
                  rules={[{ required: true, message: '请输入副柜编码！' }]}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
            </Row>

            {
              query.id && (
                <>
                  <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                    <Col md={8} sm={24}>
                      <div style={{ marginBottom: 20 }}>格口配置</div>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                    {
                      Object.keys(cellType).map((type: any) => (
                        <Col key={type} md={8} sm={24}>
                          <Form.Item
                            label={cellType[type]}
                            name={type}
                          >
                            <Select
                              mode="multiple"
                              placeholder="选择格口号"
                              onChange={this.handleChangeTypeNum}
                              style={{ width: '100%' }}
                            >
                              {
                                cellTypeNumList.map((num: number) => (
                                  <Option key={String(num)} value={num}>{num}</Option>
                                ))
                              }
                            </Select>
                          </Form.Item>
                        </Col>
                      ))
                    }
                  </Row>

                  <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                    <Col md={8} sm={24}>
                      <div style={{ marginBottom: 20 }}>位置配置</div>
                    </Col>
                  </Row>

                  <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                    {
                      Object.keys(cellPosition).map((position: any) => (
                        <Col key={position} md={8} sm={24}>
                          <Form.Item
                            label={cellPosition[position]}
                            name={position}
                          >
                            <Select
                              mode="multiple"
                              placeholder="选择格口号"
                              onChange={this.handleChangePositionNum}
                              style={{ width: '100%' }}
                            >
                              {
                                cellPositionNumList.map((num: number) => (
                                  <Option key={String(num)} value={num}>{num}</Option>
                                ))
                              }
                            </Select>
                          </Form.Item>
                        </Col>
                      ))
                    }
                  </Row>
                </>
              )
            }

            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Button
                  type="primary"
                  htmlType="submit"
                >
                  保存
                </Button>
                <Button
                  ghost
                  type="primary"
                  className="marginL16"
                  onClick={() => router.goBack()}
                >
                  取消
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>
      </Fragment>
    );
  }
}

export default DeputySaveElem;
